package com.Jin.config;

import com.Jin.pojo.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果是登录、注册页面，放行
        if (request.getRequestURI().contains("login") || request.getRequestURI().contains("register")){
            return true;           //获取地址，如果包含login，则放行，进行登录
        }

        //如果用户已登录也放行
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        if (user!=null){
            return true;
        }

        //若无登录跳转到登录页面,并且拦截
        response.sendRedirect("/");
        return false;
    }

}
